import java.util.Iterator;
import java.util.List;

/**
 * Created by patrick on 9/9/2017.
 */
public class TreeNodeHelper<T extends TreeNode> {


    /**
     * List转Tree
     * @param org 建议使用LinkedList
     * @param root
     * @return
     */

    public T transferList(List<T> org, T root) {
        if (org == null || org.size() == 0)
            return root;
        Iterator iterator = org.iterator();
        while(iterator.hasNext()){
            T node = (T)iterator.next();
            if((root.getId() == null && node.getParentId() == null) || (root.getId() != null && root.getId().equals(node.getParentId()) )){
                root.addChild(node);
//                iterator.remove();
                this.transferList(org, node);
            }
        }
        return root;
    }


    /**
     * 整理所有节点所占行数
     * 输出前必调用，建议在transferList方法后直接调用(节点变动后必须调用)
     * @param root
     * @return
     */
    public T setAllRowsCount(T root) {
        root.setRowsCount(root.getAllChildRowsCount());

        if (root.hasChild()) {
            List<T> list = root.getChildList();
            for (T child : list) {
                this.setAllRowsCount(child);
            }
        }

        return root;
    }

    public String genTable(List<T> org){
        String ret = "";
        for(T node : org){
            ret += node.genTableRow();
            if(node.hasChild()){
                ret += this.genTable(node.getChildList());
            }else {
                ret += "</tr>\n<tr>";
            }
        }
        return ret;
    }



}
